﻿using Kingdee.BOS;
using Kingdee.BOS.Authentication;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Performance.Common;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Management;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace SDWXServer.KD
{
    public class LoginViewModel
    {
        public static LoginViewModel Current { get; set; }

        public string AppID { get; set; }
        public string KDServiceSite { get; set; }
        public string DataCenterNumber { get; set; }
        public string DataCenterId { get; set; }
        public string User { get; set; }
        public string Password { get; set; }

        public string WeixinAppSubscribeMessage { get; set; }

        /// <summary>
        /// 是否登陆成功
        /// </summary>
        public bool LoginSuccessful { get; private set; }
        public string Message { get; private set; }

        public string Version { get; set; }
        /// <summary>
        /// 启用司机作为到货确认人
        /// </summary>
        public bool IsDriverAsReceiver { get; set; }
        /// <summary>
        /// 管理员手机号码
        /// </summary>
        public string AdministratorMobile { get; set; }
        /// <summary>
        /// 30:每间隔30分钟的预约点;60:整点预约
        /// </summary>
        public string YuYueTime { get; set; }

        public Context Context { get; private set; }
        public string ApiClientUserToken { get; set; }
        public Kingdee.BOS.WebApi.Client.ApiClient ApiClient { get; set; }
        public void DoLogin()
        {
            this.LoginSuccessful = false;
            this.Message = "";
            if (string.IsNullOrWhiteSpace(this.User) || string.IsNullOrWhiteSpace(this.Password))
            {
                this.Message = "请首先指定用户名和密码";
                Logger.Error(this.Message);
                return;
            }

            try
            {
                this.DataCenterId = GetDataCenterIDByNumber(this.DataCenterNumber);

                var authProxy = new SD.WRZS.K3.ServiceFacade.KDServiceClient.AuthProxy();
                authProxy.HostURL = this.KDServiceSite;
                var loginRet = authProxy.ValidateUser(this.DataCenterId, this.User, this.Password, 2052);
                if (loginRet.LoginResultType == Kingdee.BOS.Authentication.LoginResultType.Success)
                {
                    this.Context = loginRet.Context;
                    this.LoginSuccessful = true;
                }
                else if ((loginRet.LoginResultType == LoginResultType.Wanning || loginRet.LoginResultType == LoginResultType.DealWithForm) && loginRet.Context != null)
                {
                    this.Context = loginRet.Context;
                    this.LoginSuccessful = true;
                }
                else
                {
                    this.Context = null;
                    this.LoginSuccessful = false;
                    this.Message = loginRet.Message;
                }

                if (this.LoginSuccessful)
                {
                    this.KDServiceSite = Kingdee.BOS.ServiceFacade.KDServiceClient.ServiceClientConfig.KDServiceSite;
                    this.SaveConfig();

                    Logger.Info("登录金蝶云成功");
                }
                else
                {
                    Logger.Error("登录金蝶云失败：{0}", this.Message);
                }
            }
            catch (Exception e)
            {
                this.Context = null;
                this.LoginSuccessful = false;
                this.Message = e.Message;

                Logger.Error("登录金蝶云失败", e);
            }
        }
        string GetDataCenterIDByNumber(string datacenterNumber)
        {
            var dcSvr = new Kingdee.BOS.ServiceFacade.KDServiceClient.DataCenterServiceProxy();
            var dcs = dcSvr.GetDataCentersFromMC("", Kingdee.BOS.Context.DataBaseCategory.Normal);
            var dc = dcs.Where(p => p.Number.EqualsIgnoreCase(datacenterNumber)).FirstOrDefault();
            return dc != null ? dc.Id : null;
        }

        public void DoLogoff()
        {
            if (this.LoginSuccessful)
            {
                try
                {
                    var userProxy = new Kingdee.BOS.ServiceFacade.KDServiceClient.User.UserServiceProxy();
                    userProxy.Logout();
                }
                catch { }
            }

            this.LoginSuccessful = false;
            this.Context = null;
        }

        public Int64 UserId
        {
            get
            {
                return Context != null ? Context.UserId : 0L;
            }
        }

        public void LoadConfig()
        {
            this.AppID = System.Configuration.ConfigurationManager.AppSettings.Get("AppID");
            this.KDServiceSite = System.Configuration.ConfigurationManager.AppSettings.Get("KDServiceSite");
            Kingdee.BOS.ServiceFacade.KDServiceClient.ServiceClientConfig.KDServiceSite = this.KDServiceSite;

            this.DataCenterNumber = System.Configuration.ConfigurationManager.AppSettings.Get("KDDataCenter");
            this.User = System.Configuration.ConfigurationManager.AppSettings.Get("KDUser");
            this.Password = System.Configuration.ConfigurationManager.AppSettings.Get("KDPassword");

            this.WeixinAppSubscribeMessage = System.Configuration.ConfigurationManager.AppSettings.Get("WeixinAppSubscribeMessage");

            var isDriverAsReceiver = System.Configuration.ConfigurationManager.AppSettings.Get("IsDriverAsReceiver");
            if (isDriverAsReceiver != null)
            {
                this.IsDriverAsReceiver = Convert.ToBoolean(isDriverAsReceiver);
            }
            this.AdministratorMobile = System.Configuration.ConfigurationManager.AppSettings.Get("AdministratorMobile");
            if (this.AdministratorMobile == null)
            {
                this.AdministratorMobile = "";
            }
            this.YuYueTime = System.Configuration.ConfigurationManager.AppSettings.Get("YuYueTime");
            if (string.IsNullOrWhiteSpace(this.YuYueTime))
            {
                this.YuYueTime = "30";
            }
            this.ApiClient = new Kingdee.BOS.WebApi.Client.ApiClient(this.KDServiceSite);
        }
        public void SaveConfig()
        {

        }
        static object _LoginKD = new object();
        public static void CheckLogin()
        {
            lock (_LoginKD)
            {
                if (Current != null)
                {
                    if (Current.LoginSuccessful) return;

                    Current.DoLogin();
                }
            }
        }
    }
}